// pages/main/purchaseOrder/buyfinishedgoodsAdd.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        licenseplate: '',
        showIndex: null, //打开弹窗的对应下标
        height: '', //屏幕高度
        url: getApp().globalData.apiurl,
        supplierList: [], // 供应商
        goodsByList: [], // 原材料
        subForm: {}, // 提交表单
        procureId: '', // 采购单唯一id
        userinfo: {}, //当前登录人信息        
        pageState: true, // ture 表示创建采购单， false 表示修改采购单
        proCarId: null, // 唯一司机id
        carList: [], // 车辆list
    },

    delcarByList(e) {
        // console.log(this.data.carList.findIndex(item => item.licenseplate === e.target.dataset.licenseplate))
        // return;
        // this.data.carList.splice(this.data.carList.findIndex(item => item.licenseplate === e.target.dataset.licenseplate), 1)
        this.setData({
            carList: this.data.carList.filter(function (item) {
                return item.licenseplate !== e.target.dataset.licenseplate;
            })
        })
        this.setData({
            cartest: this.data.carList
        })
    },
    addCardList(e) {
        // 校验车辆号牌是否符合添加规则
        // 检索当前数组中是否包含再次输入的车牌

        // let pan = this.data.licenseplate;
        // console.log(this.data.carList.findIndex(item => {
        //     item.licenseplate === pan;
        // }));

        // console.log(this.data.licenseplate)
        // console.log(this.data.carList);
        // console.log('重复添加')
        // console.log("继续执行")
        // if (this.data.carList.findIndex(item => {
        //         item.licenseplate === this.data.licenseplate
        //     }) != -1) return wx.showToast({
        //     title: '重复添加！',
        //     icon: 'error',
        //     duration: 2000
        // });

        let ret = false;
        this.data.carList.forEach(item => {
            if (item.licenseplate === this.data.licenseplate) return ret = true;
        });
        if (ret) {
            wx.showToast({
                title: '重复添加！',
                icon: 'error',
                duration: 2000
            });
            return;
        }
        // if (this.data.licenseplate.length != 7) return '请输入正确车牌';
        if (this.data.licenseplate == undefined || this.data.licenseplate == '' || this.data.licenseplate.length != 7) return wx.showToast({
            title: '请输入正确车牌号',
            icon: 'error',
            duration: 2000
        });
        // 根据车牌号去查询当前车辆是否满足添加条件
        wx.request({
            url: this.data.url + "driverorders/driverorders/listByLicenseplate",
            method: "GET",
            data: {
                licenseplate: this.data.licenseplate
            },
            success: (res) => {
                console.log('司机信息', res);
                if (res.data.total != 0) return wx.showToast({
                    title: '司机已有订单',
                    icon: 'error',
                    duration: 2000
                });
                // 满足添加司机条件
                this.data.carList.push({
                    licenseplate: this.data.licenseplate
                });

                this.setData({
                    cartest: this.data.carList
                });
            },
            fail: () => {
                if (res.data.total != 0) return wx.showToast({
                    title: '错误！请重新进入小程序！',
                    icon: 'error',
                    duration: 2000
                });
            },
            complete: () => {
                this.setData({
                    licenseplate: ''
                })
            }
        });
    },
    getLicenseplate(e) {
        this.setData({
            licenseplate: e.detail.value
        })
    },
    // 打开弹窗
    openPopup(e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            showIndex: index,
            cartest: this.data.carList
        })
    },
    //关闭弹窗
    closePopup() {
        this.setData({
            showIndex: null
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // console.log(options.buyId);
        let id = options.buyId;
        if (id == undefined) { // 添加操作
            this.setData({
                pageState: true
            });
        } else {
            // 修改操作
            this.getInfoById(id);
            this.setData({
                pageState: false
            });
            this.getCarId(id);
        }
        this.setData({
            url: getApp().globalData.apiurl,
            procureId: this.data.pageState ? (new Date).getTime() : id,
            userinfo: getApp().globalData.userinfo
        });
        console.log('测试：', this.data.pageState ? (new Date).getTime() : id);
        // 初始化下拉数据
        this.queryDropDown();
    },

    // 提交表单
    formSubmit(e) {
        console.log(e);
        this.data.subForm = {
            ...this.data.subForm,
            ...e.detail.value,
            id: this.data.procureId
        }

        if (this.handleForm() == true) {
            // 创建采购单绑定司机的form
            let car = {
                drivername: "恒泰司机",
                licenseplate: this.data.subForm.licenseplate,
                orderid: this.data.procureId,
                ordertype: 1,
                createname: this.data.userinfo.nickName,
                id: this.data.proCarId
            }

            // 最终提交数组
            let endSubCarList = [];

            this.data.carList.forEach(item => {
                endSubCarList.push({
                    drivername: "恒泰司机",
                    licenseplate: item.licenseplate,
                    orderid: this.data.procureId,
                    ordertype: 1,
                    createname: this.data.userinfo.nickName,
                    id: this.data.proCarId
                });
            });



            if (endSubCarList.length == 0) return wx.showToast({
                title: '请绑定司机！',
                icon: 'error',
                duration: 2000
            });

            // 调用修改添加接口
            wx.request({
                url: this.data.url + 'buyfinishedgoods/buyfinishedgoods',
                method: this.data.pageState ? 'post' : 'put',
                data: this.data.subForm,
                success: res => {
                    // 添加成功后添加司机
                    if (res.data.code == 200) {
                        wx.request({
                            url: this.data.url + "driverorders/driverorders/insertDriverList",
                            method: 'post',
                            data: endSubCarList,
                            success: res => {
                                wx.showToast({
                                    title: this.data.pageState ? '采购单添加成功！' : '采购单修改成功！',
                                    icon: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    // 返回上一层
                                    wx.navigateBack({
                                        delta: 1
                                    });
                                    // : "/pages/main/purchaseOrder/buyfinishedgoodsList"
                                    // 创建完成回到首页 或者回到列表页
                                    wx.switchTab({
                                        url: "/pages/main/index"
                                    });
                                }, 1000)
                            },
                            complete: () => {},
                        });
                    }
                }
            });
        } else {
            console.log('不满足添加条件')
        }
    },
    // 得到当前采购单绑定车辆
    getCarId(id) {
        console.log(id)
        // pageSize: 10,
        // pageNum: 1,
        wx.request({
            url: this.data.url + 'driverorders/driverorders/list',
            method: "GET",
            data: {
                orderid: id,
                type: 1
            },
            success: res => {
                // 得到当绑定车辆的唯一id
                this.setData({
                    proCarId: res.data.rows[0].id,
                    carList: res.data.rows
                });
                console.log(res.data.rows)
            }
        })
    },
    // 重置表单
    formReset(e) {
        // 回退到首页
        console.log(e)
    },
    // 非空校验
    handleForm() {
        console.log(this.data.subForm);
        // 供应商  icon: 'success',
        if (this.data.subForm.supplierno == undefined) return wx.showToast({
            title: '请选择供应商！',
            icon: 'error',
            duration: 2000
        });
        // 原材料
        if (this.data.subForm.goodsno == undefined) return wx.showToast({
            title: '请选择原材料！',
            icon: 'error',
            duration: 2000
        });
        // 重量
        if (this.data.subForm.weight == undefined || this.data.subForm.weight == '') return wx.showToast({
            title: '请输入重量！',
            icon: 'error',
            duration: 2000
        });
        // 单价
        if (this.data.subForm.unitprice == undefined || this.data.subForm.unitprice == '') return wx.showToast({
            title: '请输入单价！',
            icon: 'error',
            duration: 2000
        });
        // 金额
        if (this.data.subForm.amountofmoney == undefined || this.data.subForm.amountofmoney == '') return wx.showToast({
            title: '请输入金额！',
            icon: 'error',
            duration: 2000
        });
        // console.log(typeof this.data.subForm.licenseplate)
        // console.log((this.data.subForm.licenseplate+'').length)
        // console.log(this.data.subForm.licenseplate.length)
        // 车牌号
        // if (this.data.subForm.licenseplate == undefined || this.data.subForm.licenseplate == '' || this.data.subForm.licenseplate.length != 7) return wx.showToast({
        //     title: '请输入正确车牌号',
        //     icon: 'error',
        //     duration: 2000
        // });
        let pattern = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
        if (!pattern.test(this.data.subForm.weight) ||
            !pattern.test(this.data.subForm.unitprice) ||
            !pattern.test(this.data.subForm.amountofmoney)
        ) {
            return wx.showToast({
                title: '请输入数字！',
                icon: 'error',
                duration: 2000
            });
        }
        console.log('校验完成！')
        return true;
        // 备注
        // if (this.data.subForm.remarks.length == 0) return true;
    },
    // 赋值货品编号
    goodsClick(e) {
        this.data.subForm.goodsno = e.detail.__args__[0];
        console.log(this.data.subForm);
    },
    // 供应商编号
    supplierClick(e) {
        this.data.subForm.supplierno = e.detail.__args__[0];
        console.log(this.data.subForm);
    },
    // 下拉框初始数据
    queryDropDown() {
        let _that = this;
        wx.request({
            url: _that.data.url + 'supplier/supplier/list',
            method: 'get',
            success: res => {
                _that.setData({
                    supplierList: res.data.rows
                })
            }
        });
        wx.request({
            url: _that.data.url + 'goodsmaintain/goods/list',
            method: 'get',
            data: {
                type: '1'
            },
            success: res => {
                _that.setData({
                    goodsByList: res.data.rows
                })
            }
        });
    },

    /**
     * 修改操作得到初始数据
     */
    getInfoById(buyId) {
        let _that = this;
        // 根据数据id获取当前数据条信息
        wx.request({
            url: _that.data.url + 'buyfinishedgoods/buyfinishedgoods/' + buyId,
            method: 'get',
            success: res => {
                // _that.data.userinfo = res.data.data;
                _that.setData({
                    subForm: res.data.data,
                    'subForm.goodsno': res.data.data.goodsno,
                    'subForm.supplierno': res.data.data.supplierno
                });
                // 表单绑定供应商以及原材料编号
                // supplierno
                // goodsno
                // console.log(_that.data.subForm);
            }
        });
        // let no  = wx.createSelectorQuery("supplierno");
        // console.log(no)
    },

    weightInputClick(e) {
        let val = parseFloat(JSON.parse(JSON.stringify(e.detail.value)));
        if (val != NaN) {
            this.data.subForm.weight = val;
            if (this.data.subForm.unitprice != undefined) {
                this.setData({
                    'subForm.amountofmoney': parseFloat(val * this.data.subForm.unitprice).toFixed(2)
                })
            }
        }
    },
    unitpriceInputClick(e) {
        let val = parseFloat(JSON.parse(JSON.stringify(e.detail.value)));

        if (val != NaN) {
            this.data.subForm.unitprice = val;
            if (this.data.subForm.unitprice != undefined) {
                this.setData({
                    'subForm.amountofmoney': parseFloat(val * this.data.subForm.weight).toFixed(2),
                })
            }
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        var that = this;
        // 动态获取屏幕高度
        wx.getSystemInfo({
            success: (result) => {
                that.setData({
                    height: result.windowHeight
                });
            },
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {


        // $("dt-select[name='supplierno']").attr('value', userinfo.supplierno);
        // $("dt-select[name='goodsno']").val('value', userinfo.goodsno);

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
})